package com.brian.responsibilitychain.service;


import com.brian.responsibilitychain.entity.GatewayHandlerEntity;
import com.brian.responsibilitychain.handle.GatewayHandler;
import com.brian.responsibilitychain.mapper.GatewayHandlerMapper;
import com.brian.responsibilitychain.utils.SpringBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class GatewayHandlerService {


    @Autowired
    private GatewayHandlerMapper gatewayHandlerMapper;

    private GatewayHandler firstHandler;

     public GatewayHandler getFirstGatewayHandler(){
         if(firstHandler != null){
             return firstHandler;
         }

         // 1.从数据库中查询地址hanlder
         GatewayHandlerEntity firstGatewayHandler = gatewayHandlerMapper.getFirstGatewayHandler();
         if(firstGatewayHandler == null){
                return null;
         }
         // 2.获取springboot注入容器id
         String handlerId = firstGatewayHandler.getHandlerId();
         GatewayHandler first = SpringBeanUtils.getBean(handlerId, GatewayHandler.class);
         // 3.获取下一个handler容器beanid
         String nextHandlerId = firstGatewayHandler.getNextHandlerId();
         // 4. 记录当前循环hanlder对象
         GatewayHandler gatewayHandlerTemp = first;
             while (!StringUtils.isEmpty(nextHandlerId)){
                 // 5.从springboot容器获取下一个handler对象
                 GatewayHandler gatewayHandler = SpringBeanUtils.getBean(nextHandlerId, GatewayHandler.class);
                 gatewayHandlerTemp.setNextGatewayHandler(gatewayHandler);
                 // 6.设置下一个nextHandlerId
                 GatewayHandlerEntity gatewayHandlerEntity = gatewayHandlerMapper.getByHandler(nextHandlerId);
                 if(gatewayHandlerEntity == null){
                     break;
                 }
                 nextHandlerId = gatewayHandlerEntity.getNextHandlerId();
                 gatewayHandlerTemp = gatewayHandler;
             }
         this.firstHandler = first;
         return first;
     }
}
